<?php session_start(); ?>
<?php include('misc/class_config.php'); ?>

<?php 
	include('access_control/page_access.php');	
	
	setPreviousPage();
	declinePageIfLoggedIn();
	$currentUser = new user();
?>

<?php

	$emailAddressErrorMessage = '';
	$passwordErrorMessage = '';
	$emailAddress = '';
	
	if(isset($_POST['btnLogin']))
	{
		$loginValidationError = new validation();
		$emailAddress = $_POST['email_address'];
		$emailAddressErrorMessage = $loginValidationError->isEmpty(trim($_POST['email_address']),'<label class="required">Your email address is required!</label>');
		$passwordErrorMessage = $loginValidationError->isEmpty($_POST['password'],'<label class="required">Your password is required!</label>');
		
		$loginMessage = '';
	}
	else
	{
		if(isset($_COOKIE['emailAddress']))
		{
			$emailAddress = $_COOKIE['emailAddress'];
		}
	}
?>

<?php
	if(isset($_POST['btnLogin']))
	{	
		if($loginValidationError->status == 0)
		{
			$unknownUser = new user();
			try
			{
				if($unknownUser->loginUser(trim($_POST['email_address']), md5($_POST['password'])))
				{
					$loginMessage = "logged in";
					
					$cartItem = new UserCartItem(); 
					
					$cartItem->userId = $unknownUser->id;
					$cartItemCount = $cartItem->countCartItems();
					
					if($cartItemCount !== false)
					{
						$_SESSION['cartCount'] = $cartItemCount;
					}
					
					header("Location: ".getPreviousPage());
					exit();
				}
				else
				{
					$loginMessage = '<span class="failed_login_msg>Email Address or Password is incorrect.</span>';
				}
			}
			catch(Exception $ex)
			{
				$loginMessage = '<span class="failed_login_msg>'.$ex->getMessage().'</span>';
			}
		}
	}
?>

<?php $pageTitle = "Login | Everything"; ?>
<?php include_once('layout/page_start.php'); ?>
<?php include_once('layout/page_header.php'); ?>
<?php include_once('layout/menu_bar.php'); ?></br>

	<div id="login_form_div" class="form_div">
		<form action="login.php" method="post">
			<table>
				<tr>
					<td><label>Email Address:</label></td> <td><input type="text" name="email_address" value="<?php if(!isset($_POST['btnLogin']) && isset($_COOKIE['emailAddress'])){echo $_COOKIE['emailAddress'];}else{echo $emailAddress;} ?>"/></td> <td><?php echo $emailAddressErrorMessage; ?></td>
				</tr>
				<tr>
					<td><label>Password:</label></td> <td><input type="password" name="password"/></td> <td><?php echo $passwordErrorMessage; ?></td>
				</tr>
			</table>
			<div class="form_button_div">
				<input type="submit" name="btnLogin" value="Login"/> <br/>
			</div>
			
			<div class="page_message_div"><p><?php if(isset($loginMessage)){echo $loginMessage;} ?></p></div>
		</form>
	</div>


</br></br>
<?php include('layout/page_footer.php'); ?>
<?php include('layout/page_end.php'); ?>
<?php setCurrentPage(); ?>